package rdatabase

import (
	"context"
	"fmt"
	"github.com/redis/go-redis/v9"
	"log"
)

type InitRedis struct {
	User     string `json:"user"`
	Password string `json:"Password"`
	Host     string `json:"host"`
	Port     uint   `json:"port"` //6379
	Database int    `json:"database"`
}

// Connect 连接到Redis数据库
// maxRetries：命令的最大重试次数
func (p *InitRedis) Connect(maxRetries int) *redis.Client {
	if maxRetries <= 0 {
		maxRetries = 3
	}
	_client := redis.NewClient(&redis.Options{
		Addr:       fmt.Sprintf("%v:%v", p.Host, p.Port),
		Username:   p.User,
		Password:   p.Password,
		DB:         p.Database,
		MaxRetries: maxRetries,
	})
	err := _client.Ping(context.Background()).Err()
	if err != nil {
		log.Fatal("连接 Redis 数据库", p.Database, "失败：", err)
	}
	log.Println("连接 Redis 数据库", p.Database, "完成")
	return _client
}
